#version 420

// Interpolated values from the vertex shaders
in vec2 UV;
in vec3 Position_worldspace;
in vec3 Normal_cameraspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;

out vec4 color;

// Values that stay constant for the whole mesh.
uniform sampler2D tex0;
uniform mat4 MV;

uniform vec3 lightAmb;	// ambient color of light
uniform vec3 lightDif;	// diffuse light color
uniform vec3 lightSpec; // specular color of light
uniform vec3 LightPosition_worldspace; // light position in world space

// calculate lightning
// impute : amb, dif and spec material color
vec3 calculateLightning( vec3 MaterialAmbiantColor, 
					     vec3 MaterialDiffuseColor, 
					     vec3 MaterialSpecularColor )
{
	float lightPower = 500.0f;

	// Normal of the computed fragment, in camera space
	vec3 n = normalize( Normal_cameraspace );
	// Direction of the light (from the fragment to the light)
	vec3 l = normalize( LightDirection_cameraspace );

	float cosTheta =  dot( n,l );

	if (cosTheta < 0.0)
		cosTheta = cosTheta * -1;

	// Eye vector (towards the camera)
	vec3 E = normalize(EyeDirection_cameraspace);
	// Direction in which the triangle reflects the light
	vec3 R = reflect(-l,n);
	// Cosine of the angle between the Eye vector and the Reflect vector,
	float cosAlpha = clamp( dot( E,R ), 0,1 );

	return 	MaterialAmbiantColor + 
		   	// Diffuse : "color" of the object
			MaterialDiffuseColor * lightDif  * cosTheta +
		    // Specular : reflective highlight, like a mirror
		    MaterialSpecularColor * lightSpec  * pow(cosAlpha,5);
}

void main(void)
{
	vec4 texel0;
	
	texel0 = texture( tex0, UV );
	
	if(texel0.a < 0.3)
    	discard;
    
	// Material properties
	vec3 MaterialDiffuseColor = texel0.rgb;
	vec3 MaterialAmbiantColor = vec3(0.1,0.1,0.1) * MaterialDiffuseColor;
	vec3 MaterialSpecularColor = vec3(0.05,0.05,0.05);
	
	color = vec4(calculateLightning(MaterialAmbiantColor,MaterialDiffuseColor, MaterialSpecularColor), texel0.a);

}